<template>
  <div class="reimbursement-management">
    <!-- 搜索和操作区域 -->
    <div class="operation-container">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="病人姓名">
          <el-input
            v-model="queryParams.insureName"
            placeholder="请输入病人姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="医疗卡号">
          <el-input
            v-model="queryParams.cardNumber"
            placeholder="请输入医疗卡号"
            clearable
          />
        </el-form-item>
        <el-form-item label="发票号码">
          <el-input
            v-model="queryParams.invoiceNumber"
            placeholder="请输入发票号码"
            clearable
          />
        </el-form-item>
        <el-button-group>
          <el-button
            :type="activeStatus === 0 ? 'primary' : ''"
            @click="setStatusFilter(0)"
            >待审核</el-button
          >
          <el-button
            :type="activeStatus === 1 ? 'primary' : ''"
            @click="setStatusFilter(1)"
            >已通过</el-button
          >
          <el-button
            :type="activeStatus === 2 ? 'primary' : ''"
            @click="setStatusFilter(2)"
            >已拒绝</el-button
          >
        </el-button-group>
        <el-form-item>
          <el-button
            type="primary"
            v-permission="'reimbursement:query'"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 报销表格 -->
    <el-table
      :data="reimbursementList"
      border
      stripe
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="insureName" label="病人姓名" width="120" />
      <el-table-column prop="cardNumber" label="医疗卡号" width="150" />
      <el-table-column prop="diseaseName" label="慢性病" width="120" />
      <el-table-column prop="hospitalName" label="医院" width="150" />
      <el-table-column prop="applyDate" label="申请日期" width="180">
        <template #default="{ row }">
          {{ formatDate(row.applyDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="amount" label="报销金额" width="120" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag v-if="row.status === 0" type="warning">待审核</el-tag>
          <el-tag v-else-if="row.status === 1" type="success">已通过</el-tag>
          <el-tag v-else-if="row.status === 2" type="danger">已拒绝</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="汇款状态" width="100">
        <template #default="{ row }">
          <el-tag v-if="row.isRemit === 0" type="info">未汇款</el-tag>
          <el-tag v-else-if="row.isRemit === 1" type="success">已汇款</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="auditUserName" label="审核人" width="120" />
      <el-table-column label="审核日期" width="180">
        <template #default="{ row }">
          {{ row.auditDate ? formatDate(row.auditDate) : '--' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button
            v-permission="'reimbursement:delete'"
            size="small"
            type="danger"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
          <el-button
            v-if="row.status === 0"
            v-permission="'reimbursement:audit'"
            size="small"
            type="primary"
            @click="handleAudit(row)"
          >
            审核
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <!-- 
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form
        ref="reimbursementForm"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="病人" prop="insureId">
          <el-select
            v-model="formData.insureId"
            placeholder="输入姓名搜索病人"
            filterable
            remote
            :remote-method="searchInsure"
            :loading="insureLoading"
            @change="handleInsureChange"
          >
            <el-option
              v-for="insure in insureList"
              :key="insure.id"
              :label="`${insure.insureName} (身份证 :${insure.idCard})`"
              :value="insure.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="医疗卡" prop="medicalCardId">
          <el-select
            v-model="formData.medicalCardId"
            placeholder="请选择医疗卡"
            :loading="medicalCardLoading"
            @change="handleMedicalCardChange"
          >
            <el-option
              v-for="card in medicalCardList"
              :key="card.id"
              :label="`${card.cardNumber} (医保类型: ${card.insuranceType})`"
              :value="card.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="慢性病" prop="diseaseId">
          <el-select
            v-model="formData.diseaseId"
            placeholder="请选择慢性病"
            filterable
            remote
            :remote-method="searchDisease"
            :loading="diseaseLoading"
          >
            <el-option
              v-for="disease in diseaseList"
              :key="disease.id"
              :label="disease.diseaseName"
              :value="disease.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="就诊日期" prop="treatmentDate">
          <el-date-picker
            v-model="formData.treatmentDate"
            type="date"
            placeholder="请选择就诊日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="报销金额" prop="amount">
          <el-input v-model="formData.amount" placeholder="请输入报销金额" />
        </el-form-item>
        <el-form-item label="申请日期" prop="applyDate">
          <el-date-picker
            v-model="formData.applyDate"
            type="datetime"
            placeholder="请选择申请日期"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    -->

    <!-- 审核对话框 -->
    <el-dialog v-model="auditDialogVisible" title="审核报销" width="30%">
      <el-form :model="auditForm" label-width="80px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见">
          <el-input
            v-model="auditForm.auditComment"
            type="textarea"
            :rows="3"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getReimbursementList,
  // addReimbursement,
  // updateReimbursement,
  deleteReimbursement,
  auditReimbursement
  // getReimbursementById
} from '@/api/reimbursement'
// import { getInsureList } from '@/api/insure'
// import { getDiseaseList } from '@/api/chronicDisease'
// import { getMedicalCardsByInsureId } from '@/api/medicalCard'

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  insureName: '',
  cardNumber: '',
  invoiceNumber: '',
  status: null
})

// 表格数据
const reimbursementList = ref([])
const total = ref(0)
const loading = ref(false)
const activeStatus = ref(null) // 当前选中的状态按钮

// 对话框控制
const auditDialogVisible = ref(false)
/* 
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)
*/

// 表单数据
/*
const formData = reactive({
  id: null,
  medicalCardId: null,
  insureId: null,
  diseaseId: null,
  applyDate: new Date(),
  amount: 0,
  status: 0,
  auditUserId: null,
  auditDate: null,
  auditComment: null,
  invoiceNumber: null,
  treatmentDate: null,
  isRemit: 0,
  cardNumber: null,
  insureName: null
})
*/

// 审核表单
const auditForm = reactive({
  id: null,
  status: 1,
  auditComment: ''
})

// 表单验证规则
/*
const rules = reactive({
  insureId: [{ required: true, message: '请选择病人', trigger: 'change' }],
  medicalCardId: [
    { required: true, message: '请选择医疗卡', trigger: 'change' }
  ],
  diseaseId: [{ required: true, message: '请选择慢性病', trigger: 'change' }],
  treatmentDate: [
    { required: true, message: '请选择就诊日期', trigger: 'change' }
  ],
  amount: [{ required: true, message: '请输入报销金额', trigger: 'blur' }],
  applyDate: [{ required: true, message: '请选择申请日期', trigger: 'change' }]
})
*/

// 获取报销列表
const fetchReimbursementList = async () => {
  try {
    loading.value = true
    const res = await getReimbursementList(queryParams)
    reimbursementList.value = res.data.data.records
    total.value = res.data.data.total
  } finally {
    loading.value = false
  }
}

// 设置状态筛选
const setStatusFilter = (status) => {
  activeStatus.value = status
  queryParams.status = status
  handleQuery()
}

// 搜索
const handleQuery = () => {
  queryParams.page = 1
  fetchReimbursementList()
}

// 重置搜索
const resetQuery = () => {
  Object.assign(queryParams, {
    page: 1,
    pageSize: 10,
    insureName: '',
    cardNumber: '',
    invoiceNumber: '',
    status: null
  })
  activeStatus.value = null
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchReimbursementList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  queryParams.page = val
  fetchReimbursementList()
}

// 新增报销
/*
const handleAdd = () => {
  dialogTitle.value = '新增报销'
  isAdd.value = true
  resetForm()
  dialogVisible.value = true
}
*/

// 编辑报销
/*
const handleEdit = async (row) => {
  dialogTitle.value = '编辑报销'
  isAdd.value = false

  // 获取报销详情
  const res = await getReimbursementById(row.id)
  Object.assign(formData, res.data.data)

  // 加载关联数据（确保 insureList 和 medicalCardList 已加载）
  await loadInsureData(res.data.data.insureId)
  await loadMedicalCards(res.data.data.insureId)
  await loadDiseaseData()

  // 【关键】从 insureList 中查找当前 insureId 对应的对象
  const selectedInsure = insureList.value.find(
    (item) => item.id === formData.insureId
  )
  if (selectedInsure) {
    // 手动赋值 insureName 到表单中用于显示（虽然不绑定到 select，但可用于其它用途）
    formData.insureName = selectedInsure.insureName
  }

  // 【关键】从 medicalCardList 中查找当前 medicalCardId 对应的对象
  const selectedCard = medicalCardList.value.find(
    (item) => item.id === formData.medicalCardId
  )
  if (selectedCard) {
    // 手动赋值 cardNumber 到表单中用于显示（虽然不绑定到 select，但可用于其它用途）
    formData.cardNumber = selectedCard.cardNumber
  }

  dialogVisible.value = true
}
*/

// 删除报销
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该报销记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  })
    .then(async () => {
      await deleteReimbursement(row.id)
      ElMessage.success('删除成功')
      fetchReimbursementList()
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 审核报销
const handleAudit = (row) => {
  auditForm.id = row.id
  auditForm.status = 1
  auditForm.auditComment = ''
  auditDialogVisible.value = true
}

// 提交审核
const submitAudit = async () => {
  try {
    await auditReimbursement(
      auditForm.id,
      auditForm.status,
      auditForm.auditComment
    )
    ElMessage.success('审核成功')
    auditDialogVisible.value = false
    fetchReimbursementList()
  } catch (error) {
    console.error(error)
  }
}

// 重置表单
/*
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    medicalCardId: null,
    insureId: null,
    diseaseId: null,
    applyDate: new Date(),
    amount: 0,
    status: 0,
    auditUserId: null,
    auditDate: null,
    auditComment: null,
    invoiceNumber: null,
    treatmentDate: null,
    isRemit: 0,
    cardNumber: null,
    insureName: null
  })
}
*/

// 提交表单
/*
const submitForm = async () => {
  try {
    // 校验金额
    if (
      formData.amount === null ||
      formData.amount === '' ||
      isNaN(formData.amount)
    ) {
      ElMessage.error('请输入有效的报销金额')
      return
    } else {
      formData.amount = parseFloat(formData.amount)
    }

    // 使用 formatDate 统一格式化时间字段
    if (formData.applyDate) {
      formData.applyDate = formatDate(formData.applyDate)
    }

    if (formData.treatmentDate) {
      formData.treatmentDate = formatDate(formData.treatmentDate)
    }

    // 提交数据
    if (isAdd.value) {
      await addReimbursement(formData)
      ElMessage.success('新增成功')
    } else {
      await updateReimbursement(formData)
      ElMessage.success('更新成功')
    }

    dialogVisible.value = false
    fetchReimbursementList()
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('保存失败，请检查数据格式')
  }
}
*/

// 格式化日期为 "YYYY-MM-DD HH:mm:ss"（与 Java LocalDateTime 兼容）
const formatDate = (dateString) => {
  if (!dateString) return ''

  const date = new Date(dateString)
  const pad = (n) => String(n).padStart(2, '0')

  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}

// 以下为关联表数据加载
/*
const insureList = ref([])
const insureLoading = ref(false)
const searchInsure = async (query) => {
  if (query) {
    insureLoading.value = true
    try {
      const res = await getInsureList({
        insureName: query,
        page: 1,
        pageSize: 10
      })
      insureList.value = res.data.data.records
    } finally {
      insureLoading.value = false
    }
  }
}

const medicalCardList = ref([])
const medicalCardLoading = ref(false)
const loadMedicalCards = async (insureId) => {
  if (insureId) {
    medicalCardLoading.value = true
    try {
      const res = await getMedicalCardsByInsureId(insureId)
      medicalCardList.value = res.data.data || []
    } finally {
      medicalCardLoading.value = false
    }
  } else {
    medicalCardList.value = []
  }
}
// 获取疾病列表
const diseaseList = ref([])
const diseaseLoading = ref(false)
const searchDisease = async (query) => {
  diseaseLoading.value = true
  try {
    const res = await getDiseaseList({
      diseaseName: query,
      pageSize: 100,
      page: 1
    })
    diseaseList.value = res.data.data.records
  } finally {
    diseaseLoading.value = false
  }
}

// 加载病人数据用于编辑回显
const loadInsureData = async (insureId) => {
  if (insureId) {
    const res = await getInsureList({ id: insureId })
    if (res.data.data.records.length > 0) {
      insureList.value = res.data.data.records
    }
  }
}

// 加载慢性病数据用于编辑回显
const loadDiseaseData = async () => {
  const res = await getDiseaseList({ pageSize: 100 })
  diseaseList.value = res.data.data.records
}

// 病人选择变化时加载医疗卡
const handleInsureChange = (insureId) => {
  formData.medicalCardId = null
  loadMedicalCards(insureId)
}

// 医疗卡选择变化时处理
const handleMedicalCardChange = (medicalCardId) => {
  if (!medicalCardId) return
  // 从已加载的医疗卡列表中找到选中的卡
  const selectedCard = medicalCardList.value.find(
    (card) => card.id === medicalCardId
  )
  if (selectedCard) {
    // 可以根据选中的医疗卡更新表单中的其他字段
    // 例如：设置保险类型、可报销比例等
    formData.insuranceType = selectedCard.insuranceType
  }
}
*/

// 初始化加载数据
onMounted(() => {
  fetchReimbursementList()
  // 预加载慢性病数据
  // loadDiseaseData()
})
</script>

<style scoped>
.reimbursement-management {
  padding: 20px;
}

.operation-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.button-group {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.status-buttons {
  margin-left: 15px;
}
</style>
